<template>
  <el-dialog @close="cjzjdCancel('cjzjdRuleForm')" :close-on-click-modal="false" title="出具造价单"
    :visible.sync="cjzjdVisible" width="950px">
    <div class="scroll-view">
      <el-form :model="cjzjdRuleForm" :rules="cjzjdRules" ref="cjzjdRuleForm" label-position="left" inline>
        <el-form-item label="预计开工日期" prop="start_date">
          <el-date-picker class="input-box" v-model="cjzjdRuleForm.start_date" type="date" placeholder="选择日期" clearable
            value-format="yyyy-MM-dd" :picker-options="pickerOptionsEnd" @change="cjzjdDataFunc($event, 'start')">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="预计完工日期" prop="end_date">
          <el-date-picker class="input-box" v-model="cjzjdRuleForm.end_date" type="date" clearable placeholder="选择日期"
            value-format="yyyy-MM-dd" :disabled="!cjzjdRuleForm.start_date" :picker-options="pickerOptions_"
            @change="cjzjdDataFunc($event, 'end')">
          </el-date-picker>
        </el-form-item>
        <el-form-item v-if="cjzjdRuleForm.duration_days" label="工期天数" prop="duration_days">
          <el-input class="input-box" v-model="cjzjdRuleForm.duration_days" disabled clearable><span
              slot="suffix">天</span></el-input>
        </el-form-item>
        <el-form-item label="建筑面积" prop="building_area">
          <el-input class="input-box" placeholder="单位（m²）" clearable v-input-limit="2"
            v-model="cjzjdRuleForm.building_area"></el-input>
        </el-form-item>
        <el-form-item label="基础装修费" prop="basic_decoration_fee">
          <el-input class="input-box" @input="cjzjdInputChange" clearable v-input-limit="2"
            v-model="cjzjdRuleForm.basic_decoration_fee"></el-input>
        </el-form-item>
        <el-form-item label="主材采购费" prop="material_costs">
          <el-input class="input-box" @input="cjzjdInputChange" clearable v-input-limit="2"
            v-model="cjzjdRuleForm.material_costs"></el-input>
        </el-form-item>
        <el-form-item label="报价税金" prop="quotation_taxes">
          <el-input class="input-box" @input="cjzjdInputChange" clearable v-input-limit="2"
            v-model="cjzjdRuleForm.quotation_taxes"></el-input>
        </el-form-item>
        <el-form-item label="现场采购成本" prop="procurement_cost">
          <el-input class="input-box" @input="cjzjdInputChange" clearable v-input-limit="2"
            v-model="cjzjdRuleForm.procurement_cost"></el-input>
        </el-form-item>
        <el-form-item label="公司集采成本" prop="centralized_procurement_cost">
          <el-input class="input-box" @input="cjzjdInputChange" clearable v-input-limit="2"
            v-model="cjzjdRuleForm.centralized_procurement_cost"></el-input>
        </el-form-item>
        <el-form-item label="管理成本" prop="management_costs">
          <el-input class="input-box" @input="cjzjdInputChange" clearable v-input-limit="2"
            v-model="cjzjdRuleForm.management_costs"></el-input>
        </el-form-item>
        <el-form-item label="报价金额" prop="quotation_amount">
          <el-input class="input-box" @input="cjzjdInputChange" clearable disabled v-input-limit="2"
            v-model="cjzjdRuleForm.quotation_amount"></el-input>
        </el-form-item>
        <el-form-item label="成本金额" prop="cost_amount">
          <el-input class="input-box" @input="cjzjdInputChange" clearable disabled v-input-limit="2"
            v-model="cjzjdRuleForm.cost_amount"></el-input>
        </el-form-item>
        <el-form-item label="利润金额" prop="profit_amount">
          <el-input class="input-box" clearable disabled v-input-limit="2"
            v-model="cjzjdRuleForm.profit_amount"></el-input>
        </el-form-item>
        <el-form-item label="利润率(报价)" prop="profit_ratio">
          <el-input class="input-box" clearable disabled v-input-limit="2" v-model="cjzjdRuleForm.profit_ratio"><span
              slot="suffix">%</span></el-input>
        </el-form-item>
        <el-form-item label="报价类型" prop="quotation_type">
          <el-select filterable class="input-box" v-model="cjzjdRuleForm.quotation_type" placeholder="请选择">
            <el-option v-for="item in quotationTypeOptions" clearable :key="item.value" :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input :rows="1" class="input-box" v-model="cjzjdRuleForm.remark" type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="报价单文件 (.ppt,.xls,.pdf,.doc,.docx,.xlsx)" prop="quotation_file">
          <el-input style="position: absolute; z-index: 0; top: -999999px"
            v-model="cjzjdRuleForm.quotation_file.length"></el-input>
          <el-upload accept=".ppt,.xls,.pdf,.doc,.docx,.xlsx" :on-change="(file, fileList) => {
      cjzjdChangeFile(file, fileList, 'quotation_file');
    }
    " :on-remove="(file, fileList) => {
      cjzjdFileRemove(file, fileList, 'quotation_file');
    }
    " :auto-upload="false" :file-list="cjzjdRuleForm.quotation_file" action="#">
            <el-button size="small" icon="el-icon-plus">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="利润单文件 (.ppt,.xls,.pdf,.doc,.docx,.xlsx)" prop="profit_statement_file">
          <el-input style="position: absolute; z-index: 0; top: -999999px"
            v-model="cjzjdRuleForm.profit_statement_file.length"></el-input>
          <el-upload accept=".ppt,.xls,.pdf,.doc,.docx,.xlsx" :on-change="(file, fileList) => {
      cjzjdChangeFile(file, fileList, 'profit_statement_file');
    }
    " :on-remove="(file, fileList) => {
      cjzjdFileRemove(file, fileList, 'profit_statement_file');
    }
    " :auto-upload="false" :file-list="cjzjdRuleForm.profit_statement_file" action="#">
            <el-button size="small" icon="el-icon-plus">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="成本单文件 (.ppt,.xls,.pdf,.doc,.docx,.xlsx)" prop="cost_list_file">
          <el-input style="position: absolute; z-index: 0; top: -999999px"
            v-model="cjzjdRuleForm.cost_list_file.length"></el-input>
          <el-upload accept=".ppt,.xls,.pdf,.doc,.docx,.xlsx" :on-change="(file, fileList) => {
      cjzjdChangeFile(file, fileList, 'cost_list_file');
    }
    " :on-remove="(file, fileList) => {
      cjzjdFileRemove(file, fileList, 'cost_list_file');
    }
    " :auto-upload="false" :file-list="cjzjdRuleForm.cost_list_file" action="#">
            <el-button size="small" icon="el-icon-plus">点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
    </div>
    <span slot="footer">
      <el-button @click="cjzjdCancel('cjzjdRuleForm')">关闭</el-button>
      <el-button type="primary" @click="cjzjdSubmit('cjzjdRuleForm')" :disabled="diaLoading" :loading="diaLoading">确
        定</el-button>
    </span>
  </el-dialog>
</template>
<script>
import projectApi from "@/api/projectApi";
import companyApi from "@/api/companyApi";
import adminApi from "@/api/adminApi";
import { getUserInfo } from "@/utils/auth";
import foremanApi from "@/api/foremanApi";
import * as math from "mathjs";

export default {
  name: "",
  props: {
    addDialogVisible: {
      type: Boolean,
      default: false,
      required: false,
    },
    project_id: {
      required: false,
    },
    // 历史造价记录
    hisQuotationData: {
      required: false,
    },
    // 报价开工，完工日期
    startEndDate: {
      required: false,
    },
  },
  data() {
    var quotation_file = (rule, value, callback) => {
      if (!value.length) {
        callback(new Error("请上传报价单文件"));
      } else {
        callback();
      }
    };
    var profit_statement_file = (rule, value, callback) => {
      if (!value.length) {
        callback(new Error("请上传利润单文件"));
      } else {
        callback();
      }
    };
    var cost_list_file = (rule, value, callback) => {
      if (!value.length) {
        callback(new Error("请上传成本单文件"));
      } else {
        callback();
      }
    };
    return {
      cjzjdVisible: false,
      cjzjdRules: {
        start_date: {
          required: true,
          message: "请选择开工日期",
          trigger: "change",
        },
        end_date: {
          required: true,
          message: "请选择完工日期",
          trigger: "change",
        },
        duration_days: {
          required: true,
          message: "请输入工期天数",
          trigger: "change",
        },
        building_area: {
          required: true,
          message: "请输入建筑面积",
          trigger: "change",
        },
        quotation_amount: {
          required: true,
          message: "请输入报价金额",
          trigger: "change",
        },
        basic_decoration_fee: {
          required: true,
          message: "请输入基础装修费用",
          trigger: "change",
        },
        material_costs: {
          required: true,
          message: "请输入主材采购费用",
          trigger: "change",
        },
        quotation_taxes: {
          required: true,
          message: "请输入报价税金",
          trigger: "change",
        },
        cost_amount: {
          required: true,
          message: "请输入成本金额",
          trigger: "change",
        },
        procurement_cost: {
          required: true,
          message: "请输入现场采购成本",
          trigger: "change",
        },
        centralized_procurement_cost: {
          required: true,
          message: "请输入公司集采成本",
          trigger: "change",
        },
        management_costs: {
          required: true,
          message: "请输入管理成本",
          trigger: "change",
        },
        profit_amount: {
          required: true,
          message: "请输入利润金额",
          trigger: "change",
        },
        profit_ratio: {
          required: true,
          message: "请输入利润率(报价)",
          trigger: "change",
        },
        quotation_type: {
          required: true,
          message: "请选择报价类型",
          trigger: "change",
        },

        quotation_file: {
          required: true,
          validator: quotation_file,
          trigger: "change",
        },
        profit_statement_file: {
          required: true,
          validator: profit_statement_file,
          trigger: "change",
        },
        cost_list_file: {
          required: true,
          validator: cost_list_file,
          trigger: "change",
        },
        remark: "",
      },
      cjzjdRuleForm: {
        start_date: "",
        end_date: "",
        duration_days: "",
        building_area: "",
        quotation_amount: "",
        basic_decoration_fee: "",
        material_costs: "",
        quotation_taxes: "",
        cost_amount: "",
        procurement_cost: "",
        centralized_procurement_cost: "",
        management_costs: "",
        profit_amount: "",
        quotation_type: "",
        quotation_file: [],
        profit_statement_file: [],
        cost_list_file: [],
        profit_ratio: "",
        remark: "",
      },
      pickerOptionsStart: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
      },
      pickerOptionsEnd: {
        disabledDate(time) {
          return time.getTime() < Date.now();
        },
      },
      pickerOptions_: {},
      quotationTypeOptions: [
        {
          value: 1,
          label: "基础施工报价（首次）",
        },
        {
          value: 2,
          label: "基础施工报价（调整）",
        },
        // {
        //   value: 3,
        //   label: "增减项施工报价",
        // },
      ],
      diaLoading: false,
    };
  },
  watch: {
    addDialogVisible(val1, val2) {
      this.cjzjdVisible = this.addDialogVisible;
      console.log(this.startEndDate, this.hisQuotationData);
      if (
        this.addDialogVisible &&
        this.startEndDate &&
        !this.hisQuotationData
      ) {
        this.cjzjdRuleForm.start_date = this.startEndDate.start_date;
        this.cjzjdRuleForm.end_date = this.startEndDate.end_date;
        const date1 = new Date(this.cjzjdRuleForm.start_date);
        const date2 = new Date(this.cjzjdRuleForm.end_date);
        this.cjzjdRuleForm.duration_days = this.daysBetween(date1, date2) + 1;
      }
      if (this.hisQuotationData && this.addDialogVisible) {
        let hisQuotationData = this.hisQuotationData;
        this.cjzjdRuleForm = {
          start_date: hisQuotationData.start_date,
          end_date: hisQuotationData.end_date,
          duration_days: hisQuotationData.duration_days,
          building_area: hisQuotationData.building_area,
          quotation_amount: hisQuotationData.quotation_amount,
          basic_decoration_fee: hisQuotationData.basic_decoration_fee,
          material_costs: hisQuotationData.material_costs,
          quotation_taxes: hisQuotationData.quotation_taxes,
          cost_amount: hisQuotationData.cost_amount,
          procurement_cost: hisQuotationData.procurement_cost,
          centralized_procurement_cost:
            hisQuotationData.centralized_procurement_cost,
          management_costs: hisQuotationData.management_costs,
          profit_amount: hisQuotationData.profit_amount,
          quotation_type: hisQuotationData.quotation_type,
          quotation_file: [],
          profit_statement_file: [],
          cost_list_file: [],
          profit_ratio: hisQuotationData.profit_ratio,
          remark: hisQuotationData.remark,
        };
      }
    },
  },
  computed: {},
  mounted() { },
  methods: {
    // 出具造价单
    cjzjdCancel(formName) {
      this.cjzjdRuleForm = {
        start_date: "",
        end_date: "",
        duration_days: "",
        building_area: "",
        quotation_amount: "",
        basic_decoration_fee: "",
        material_costs: "",
        quotation_taxes: "",
        cost_amount: "",
        procurement_cost: "",
        centralized_procurement_cost: "",
        management_costs: "",
        profit_amount: "",
        quotation_type: "",
        quotation_file: [],
        profit_statement_file: [],
        cost_list_file: [],
        profit_ratio: "",
        remark: "",
      };
      this.$nextTick(() => {
        this.$refs[formName].clearValidate();
        this.$emit("onClose", true);
      });
    },
    cjzjdDataFunc(e, type) {
      let cjzjdRuleForm = this.cjzjdRuleForm;
      if (type == "start") {
        if (cjzjdRuleForm.start_date) {
          this.pickerOptions_ = {
            disabledDate(time) {
              return (
                time.getTime() < new Date(cjzjdRuleForm.start_date).getTime()
              );
            },
          };
        } else {
          cjzjdRuleForm.end_date = "";
        }
      }
      if (cjzjdRuleForm.start_date && cjzjdRuleForm.end_date) {
        const date1 = new Date(cjzjdRuleForm.start_date);
        const date2 = new Date(cjzjdRuleForm.end_date);
        if (!this.compareDates(date1, date2)) {
          this.$message.warning("完工日期需晚于开工日期");
          type == "start"
            ? (cjzjdRuleForm.start_date = "")
            : (cjzjdRuleForm.end_date = "");
          cjzjdRuleForm.duration_days = "";
          this.cjzjdRuleForm = cjzjdRuleForm;
          return;
        }
        cjzjdRuleForm.duration_days = this.daysBetween(date1, date2) + 1;
      } else {
        cjzjdRuleForm.duration_days = "";
      }
      this.cjzjdRuleForm = cjzjdRuleForm;
    },
    cjzjdSubmit(formName) {
      let cjzjdRuleForm = this.cjzjdRuleForm;
      console.log(cjzjdRuleForm, "出具造价单参数");
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let formdata = new FormData();
          formdata.append(
            "data",
            JSON.stringify({
              project_id: this.project_id,
              remark: cjzjdRuleForm.remark,
              start_date: cjzjdRuleForm.start_date,
              end_date: cjzjdRuleForm.end_date,
              duration_days: cjzjdRuleForm.duration_days,
              building_area: cjzjdRuleForm.building_area,
              quotation_amount: cjzjdRuleForm.quotation_amount,
              basic_decoration_fee: cjzjdRuleForm.basic_decoration_fee,
              material_costs: cjzjdRuleForm.material_costs,
              quotation_taxes: cjzjdRuleForm.quotation_taxes,
              cost_amount: cjzjdRuleForm.cost_amount,
              procurement_cost: cjzjdRuleForm.procurement_cost,
              centralized_procurement_cost:
                cjzjdRuleForm.centralized_procurement_cost,
              management_costs: cjzjdRuleForm.management_costs,
              profit_amount: cjzjdRuleForm.profit_amount,
              quotation_type: cjzjdRuleForm.quotation_type,
              profit_ratio: cjzjdRuleForm.profit_ratio,
            })
          );
          cjzjdRuleForm.quotation_file.forEach((item) => {
            formdata.append("quotation_file[]", item.raw);
          });
          cjzjdRuleForm.profit_statement_file.forEach((item) => {
            formdata.append("profit_statement_file[]", item.raw);
          });
          cjzjdRuleForm.cost_list_file.forEach((item) => {
            formdata.append("cost_list_file[]", item.raw);
          });
          this.diaLoading = true;
          projectApi
            .issueQuotation(formdata)
            .then((res) => {
              console.log(res, "出具造价单");
              this.diaLoading = false;
              if (res.code == 200) {
                this.$emit("onSuccess", true);
              }
              this.$message({
                type: res.code == 200 ? "success" : "warning",
                message: res.code == 200 ? "处理成功" : res.message,
              });
            })
            .catch((err) => {
              this.diaLoading = false;
              this.$message({
                type: "warning",
                message: err.message,
              });
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    cjzjdChangeFile(file, fileList, type) {
      console.log(file, fileList, type);
      let cjzjdRuleForm = this.cjzjdRuleForm;
      cjzjdRuleForm[type] = [file];
      this.cjzjdRuleForm = cjzjdRuleForm;
    },
    cjzjdFileRemove(file, fileList, type) {
      console.log(file, fileList, type);
      let cjzjdRuleForm = this.cjzjdRuleForm;
      cjzjdRuleForm[type] = fileList;
      this.cjzjdRuleForm = cjzjdRuleForm;
    },
    cjzjdInputChange() {
      // 金额计算
      let cjzjdRuleForm = this.cjzjdRuleForm;
      let basic_decoration_fee = cjzjdRuleForm.basic_decoration_fee || 0; //基础装修费
      let material_costs = cjzjdRuleForm.material_costs || 0; ///主材采购费用
      let quotation_taxes = cjzjdRuleForm.quotation_taxes || 0; //报价税金
      let quotation_amount = 0; //报价金额
      quotation_amount = math.format(
        math.add(
          math.bignumber(basic_decoration_fee),
          math.bignumber(material_costs),
          math.bignumber(quotation_taxes)
        )
      );
      quotation_amount = ((quotation_amount * 100) / 100).toFixed(2);
      cjzjdRuleForm.quotation_amount = quotation_amount;

      let procurement_cost = cjzjdRuleForm.procurement_cost || 0; //现场采购成本
      let centralized_procurement_cost =
        cjzjdRuleForm.centralized_procurement_cost || 0; //公司集采成本
      let management_costs = cjzjdRuleForm.management_costs || 0; //管理成本
      let cost_amount = 0; //成本金额
      cost_amount = math.format(
        math.add(
          math.bignumber(procurement_cost),
          math.bignumber(centralized_procurement_cost),
          math.bignumber(management_costs),
          math.bignumber(quotation_taxes)
        )
      );
      cost_amount = ((cost_amount * 100) / 100).toFixed(2);
      cjzjdRuleForm.cost_amount = cost_amount;

      let profit_amount = 0; //利润金额
      let profit_ratio = 0; //利润率
      let all_costs = 0; //总成本
      all_costs = math.format(
        math.add(
          math.bignumber(procurement_cost),
          math.bignumber(centralized_procurement_cost),
          math.bignumber(management_costs),
          math.bignumber(quotation_taxes)
        )
      );
      all_costs = ((all_costs * 100) / 100).toFixed(2); //总成本
      profit_amount = math.format(
        math.subtract(
          math.bignumber(quotation_amount),
          math.bignumber(all_costs)
        )
      );
      profit_amount = ((profit_amount * 100) / 100).toFixed(2);
      cjzjdRuleForm.profit_amount = profit_amount;

      profit_ratio = math.format(
        math.divide(math.bignumber(profit_amount), math.bignumber(all_costs))
      );
      profit_ratio = (profit_ratio * 100).toFixed(2)
      cjzjdRuleForm.profit_ratio = profit_ratio;
      // console.log(profit_ratio, "利润率");
      // console.log(all_costs,"总成本");
      // console.log(profit_amount,"利润金额");

      this.cjzjdRuleForm = cjzjdRuleForm;
    },
    compareDates(date1, date2) {
      return date1.getTime() - date2.getTime() < 0;
    },
    daysBetween(date1, date2) {
      const oneDay = 24 * 60 * 60 * 1000; // 每天的毫秒数
      const firstTime = date1.getTime();
      const secondTime = date2.getTime();

      return Math.round(Math.abs((firstTime - secondTime) / oneDay));
    },
  },
};
</script>
<style lang="scss" scoped>
@import "./index.scss";
</style>